const connection = require('../app/database')

class MommentService {
  // 添加动态
  async create(content, userId) {
    const statement = "insert into moment (content, user_id) values (?, ?)"
    const [result] = await connection.execute(statement, [content, userId])
    return result
  }
  // 修改动态
  async update(content, id) {
    const statement = `update moment set content = ? where id = ?`
    const [result] = await connection.execute(statement, [content, id])
    return result
  }
  // 删除动态
  async remove(id) {
    const statement = `delete from moment where id = ?`
    try {
      const [result] = await connection.execute(statement, [id])
      return result
    } catch (error) {
      console.log(error.message)
    }
  }
  // 获取动态列表
  async list(offset, limit) {
    const statement = `
      select m.id id, m.content content, m.createAt createAt,
      JSON_OBJECT('id', u.id, 'username', u.username) author
      from moment m LEFT JOIN users u
      on m.user_id = u.id
      LIMIT ?, ?;
    `
    try {
      const [result] = await connection.execute(statement, [offset, limit])
    return result
    } catch (error) {
      console.log(error.message)
    }
  }
  // 获取用户的动态列表
  async listByUser(userId, offset, limit) {
    const statement = `
      select m.id id, m.content content, m.createAt createAt,
      JSON_OBJECT('id', u.id, 'username', u.username) author
      from moment m LEFT JOIN users u
      on m.user_id = u.id
      WHERE m.user_id = ?
      LIMIT ?, ?
    `
    const [result] = await connection.execute(statement, [userId, offset, limit])
    return result
  }
  // 根据id获取动态详细内容
  async getMomentById(momentId) {
    const statement = `
      select m.id id, m.content content, m.createAt createAt,
      JSON_OBJECT('id', u.id, 'username', u.username) author
      from moment m
      LEFT JOIN users u
      ON m.user_id = u.id
      WHERE m.id = ?;
    `
    try {
      const [result] = await connection.execute(statement, [momentId])
      return result
    } catch (error) {
      console.log(error.message)      
      return
    }
  }
}

module.exports = new MommentService()